import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';

const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL, // 确保 VITE_API_URL 正确配置
  timeout: 1000,
  headers: { 'Content-Type': 'application/json' },
});

// 请求拦截器
service.interceptors.request.use(
  (config: any) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers = {
        ...config.headers,
        Authorization: `Bearer ${token}`,
      };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;
    if (res.code !== 0) {
      return Promise.reject(new Error(res.message || 'error'));
    }
    return res;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 导出封装请求方法
export const get = <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => {
  return service.get(url, { params, ...config });
};

export const post = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
  return service.post(url, data, { ...config });
};

export default service;
